// scripts/app.js
document.addEventListener('DOMContentLoaded', () => {
    initializeApp();
});

function initializeApp() {
    // 初始化路由
    initRouter();
    // 初始化用户状态
    initAuth();
    // 初始化数据
    initChartData();
    // 初始化表格
    initDataTable();
}

function initRouter() {
    const sidebarLinks = document.querySelectorAll('.sidebar a');
    const contentArea = document.getElementById('content-area');
    
    sidebarLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const page = e.target.dataset.page;
            loadPage(page);
        });
    });

    function loadPage(page) {
        fetch(`pages/${page}.html`)
            .then(response => response.text())
            .then(html => {
                contentArea.innerHTML = html;
                // 页面加载后执行特定初始化
                switch(page) {
                    case 'chart':
                        initChartData();
                        break;
                    case 'data':
                        initDataTable();
                        break;
                }
            });
    }
}

// 用户认证模块
function initAuth() {
    const user = localStorage.getItem('currentUser');
    const userInfo = document.getElementById('user-info');
    const logoutBtn = document.getElementById('logoutBtn');
    
    if(user) {
        const userData = JSON.parse(user);
        userInfo.textContent = `欢迎，${userData.username}`;
        logoutBtn.style.display = 'inline-block';
    } else {
        logoutBtn.style.display = 'none';
    }

    logoutBtn.addEventListener('click', () => {
        localStorage.removeItem('currentUser');
        location.reload();
    });
}

// 数据可视化模块
let chartData = {
    scatter: {
        x: [1, 2, 3, 4, 5],
        y: [2, 3, 5, 7, 11],
        type: 'scatter'
    },
    line: {
        x: [1, 2, 3, 4, 5],
        y: [2, 4, 6, 8, 10],
        type: 'scatter',
        mode: 'lines+markers'
    }
};

function initChartData() {
    generateChart('scatter');
}

function generateChart(type) {
    const plotDiv = document.getElementById('scatter-plot');
    const data = [chartData[type]];
    
    Plotly.newPlot(plotDiv, data, {
        title: `示例${type === 'scatter' ? '散点图' : '折线图'}`,
        xaxis: {title: 'X轴'},
        yaxis: {title: 'Y轴'}
    });
}

// 数据管理模块
let dataTable = JSON.parse(localStorage.getItem('dataTable')) || [];

function initDataTable() {
    renderTable();
    setupTableEvents();
}

function renderTable() {
    const tbody = document.getElementById('table-body');
    tbody.innerHTML = dataTable.map((row, index) => `
        <tr>
            <td contenteditable="false">${row.name}</td>
            <td contenteditable="false">${row.age}</td>
            <td contenteditable="false">${row.email}</td>
            <td contenteditable="false">${row.interest}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editRow(${index})">编辑</button>
                <button class="btn btn-sm btn-danger" onclick="deleteRow(${index})">删除</button>
            </td>
        </tr>
    `).join('');
}

function setupTableEvents() {
    document.getElementById('table-body').addEventListener('click', (e) => {
        const target = e.target;
        if(target.classList.contains('edit-btn')) {
            toggleEdit(target.closest('tr'));
        }
    });
}

function addNewRow() {
    dataTable.push({
        name: '',
        age: '',
        email: '',
        interest: ''
    });
    renderTable();
}

function deleteRow(index) {
    dataTable.splice(index, 1);
    renderTable();
    saveData();
}

function editRow(index) {
    const row = document.querySelectorAll('#table-body tr')[index];
    const cells = row.querySelectorAll('td');
    
    cells.forEach((cell, i) => {
        if(i < 4) {
            cell.contentEditable = cell.contentEditable === 'true' ? 'false' : 'true';
            cell.classList.toggle('editing');
        }
    });
}

function saveData() {
    localStorage.setItem('dataTable', JSON.stringify(dataTable));
    Swal.fire({
        title: '保存成功',
        icon: 'success',
        timer: 1500
    });
}

function exportToCSV() {
    const csvContent = "data:text/csv;charset=utf-8," + 
        "姓名,年龄,邮箱,兴趣领域\n" + 
        dataTable.map(row => 
            `${row.name},${row.age},${row.email},${row.interest}`
        ).join('\n');
    
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', 'data.csv');
    link.click();
}

// 页面滚动效果
window.addEventListener('scroll', () => {
    const backToTop = document.querySelector('.back-to-top');
    if(window.pageYOffset > 300) {
        backToTop.classList.add('show');
    } else {
        backToTop.classList.remove('show');
    }
});
